import { Tsrv, ts } from '@/services';
import { N_cAnalyzer } from './type';

class T_cmd {
  // 主组件实例
  private self: N_cAnalyzer.cAnalyzer;
  // 主组refs

  private task = new ts.T_task(10000);

  // 当前轮询是否开启
  public isOpenTask: boolean = false;

  // 主组件created里初始化
  public init(self: any) {
    this.self = self;
  }

  public getTcmd(): T_cmd {
    return this;
  }

  public startTask() {
    this.task.addTask(this.readData);
    this.task.startTask();
    this.isOpenTask = true;
  }

  public stopTask() {
    this.task.delTask(this.readData);
    this.task.stopTask();
    this.isOpenTask = false;
  }

  private readData = () => {
    // Tsrv.readPlcData(this.self.ecDetCodes).then(data => {
    //   if (typeof data === 'boolean') return;
    //   for (const el of this.self.tableData) {
    //     Object.keys(el).forEach(key => {
    //       if (!Tsrv.noValue(el[key].code)) {
    //         el[key].value = data[el[key].code].v;
    //       }
    //     });
    //   }
    // });

    const chunkSize = 20;
    const chunks = [];
    for (let i = 0; i < this.self.ecDetCodes.length; i += chunkSize) {
      chunks.push(this.self.ecDetCodes.slice(i, i + chunkSize));
    }

    const promises = chunks.map(chunk => Tsrv.readPlcData(chunk));
    Promise.all(promises).then(results => {
      const combinedResult = Object.assign({}, ...results);
      if (typeof combinedResult !== 'boolean') {
        for (const el of this.self.tableData) {
          Object.keys(el).forEach(key => {
            if (!Tsrv.noValue(el[key].code)) {
              el[key].value = combinedResult[el[key].code].v;
            }
          });
        }
        this.self.sulfuricNum.value =
          combinedResult[this.self.sulfuricNum.code].v;
      }
    });
  };
}
interface I_cmd extends T_cmd {}
export { I_cmd, T_cmd };
